<template>
  <view id="position">
    <view class="map-container"
      ><map
        :latitude="latitude"
        :longitude="longitude"
        :markers="covers"
        :circles="circles"
        v-if="covers.length > 0"
      ></map
    ></view>
    <view v-if="listData" style="display: flex" class="search-container">
      <view :style="searchFalg ? 'width:89%;' : 'width:100%;'">
        <uni-search-bar
          cancelText=" "
          @blur="blur"
          @input="input"
          @focus="searchFalg = true"
          @confirm="confirmSearch"
          @cancel="cancel"
          @clear="confirmClear"
        ></uni-search-bar>
      </view>
      <view
        v-show="searchFalg"
        style="width: 11%; display: flex; align-items: center; font-size: 26rpx"
      >
        搜索
      </view>
    </view>
    <!-- @input="input" -->
    <view class="list">
      <scroll-view 
    scroll-y 
     class="list-scroll-view"
      :style="{height: scrollHeight + 'px'}"
  >
      <uni-collapse ref="treeRef" accordion v-if="listData">
        <uni-collapse-item
          v-show="item.children.length > 0"
          v-for="item in listData"
          :key="`item${item.id}`"
          :title="item.name"
        >
        <uni-collapse class="list2" v-if="item.children">
          <uni-collapse-item v-show="item2.children.length > 0"
          v-for="item2 in item.children"
          :key="`item2${item2.id}`"
          :title="item2.name">
            <view class="content">
            <uni-list>
              <uni-list-item
                v-for="child in item2.children"
                :key="`child${child.id}`"
                :title="child.name"
              >
                <template v-slot:footer>
                  <checkbox
                    :value="child.id + ''"
                    :checked="child.id == typeId"
                    style="transform: scale(0.7)"
                    @click="
                      handleClick(
                        $event,
                        child.id,
                        child.name,
                        child.randomPostion,
                        child
                      )
                    "
                  />
                </template>
              </uni-list-item>
            </uni-list>
          </view>
          </uni-collapse-item>
        </uni-collapse>
        </uni-collapse-item>
        <view class="noData" v-if="listDataFlag">暂无数据</view>
      </uni-collapse>
      </scroll-view>
    </view>
    <view class="bottom-nav" v-if="isCode == false"
      ><button type="primary" class="btn" @click="next">下一步</button></view
    >
  </view>
</template>

<script>
import { getTypes } from "@/api/sample/index";
import { getValueByCode } from "@/api/sampleCheck/index";
import uniCollapse from '../../uni_modules/uni-collapse/components/uni-collapse/uni-collapse.vue';
export default {
  components: { uniCollapse },
  data() {
    return {
      // 项目信息
      projectInfo: {},
      // 检测分类option
      listData: null,
      // 选中分类
      typeId: "",
      typeName: "",
      // 是否生成随机框
      randomPostion: "",
      // 随机框数量
      specimenNums: "",
      // 定位经纬度
      latitude: undefined,
      longitude: undefined,
      // 定位点-地图上显示
      covers: [],
      circles: [],
      byCode: "",
      isCode: false,
      hintShow: false,
      searchData: "",
      listDataOriginal: null,
      listDataFlag: false,
      searchFalg: false,
      scrollHeight: '500' // 初始估算值
    };
  },
  onReady() {
    this.projectInfo = uni.getStorageSync("projectInfo");
    this.latitude = this.projectInfo.latitude;
    this.longitude = this.projectInfo.longitude;
    this.covers.push({
      latitude: this.latitude,
      longitude: this.longitude,
      width: 48,
      height: 48,
      iconPath: "../../static/img/location.png",
    });
    this.getTypes();
    this.getValueByCodes();
  },
  watch: {
    searchData(val) {
      if (val.length == 0) {
        this.listDataFlag = false;
        this.listData = this.listDataOriginal;
      }
    },
  },
  mounted() {
    this.calcScrollHeight();
    // 监听窗口变化（如键盘弹出）
    uni.onWindowResize(() => this.calcScrollHeight());
  },
  methods: {
    getValueByCodes() {
      let data = {
        code: "isCheckProjectMapRange",
      };
      getValueByCode(data).then((res) => {
        console.log(res, "res", 1);
        if (res.code == 200) {
          console.log(res, "res", 3);
          this.byCode = res.data.value;
          console.log(res);
          this.initPosition();
        }
      });
    },
    // 复选框单选
    handleClick($event, id, name, randomPostion, child) {
      console.log(randomPostion, "randomPostion", child);
      this.typeId = id;
      this.typeName = name;
      this.randomPostion = randomPostion;
      this.specimenNums = child.specimenNums;
    },
     // 动态计算滚动高度
    calcScrollHeight() {
      return new Promise(resolve => {
    const query = uni.createSelectorQuery().in(this);
    
    query.select('.container').boundingClientRect(container => {
      if (!container) {
        this.scrollHeight = 500; // 默认值
        return resolve();
      }
      
      query.select('.map-container').boundingClientRect(map => {
        query.select('.search-container').boundingClientRect(search => {
          const mapHeight = map?.height || 0;
          const searchHeight = search?.height || 0;
          
          // 计算最终高度（至少保留100px）
          this.scrollHeight = Math.max(
            container.height - mapHeight - searchHeight - 20,
            100
          );
          
          resolve();
        }).exec();
      }).exec();
    }).exec();
  });
    },
    // 获取当前定位
    initPosition() {
      uni.showLoading({
        mask: true,
        title: "获取定位中...",
      });
      uni.getLocation({
        type: "gcj02",
        success: (res) => {
          uni.hideLoading();
          console.log(res, "res");
          this.longitude = res.longitude;
          this.latitude = res.latitude;
          this.covers.push({
            latitude: res.latitude,
            longitude: res.longitude,
            // latitude: 29.57592,
            // longitude: 106.730822,
            width: 48,
            height: 48,
            iconPath: "../../static/img/location.png",
          });
          // 添加500米范围圆
          this.circles = [
            {
              latitude: res.latitude,
              longitude: res.longitude,
              color: "#00AAFF22", // 圆圈颜色
              fillColor: "#00AAFF22", // 填充颜色
              radius: 500, // 半径500米
              strokeWidth: 1, // 边框宽度
            },
          ];
          let point1 = new plus.maps.Point(res.longitude, res.latitude);
          console.log(
            this.projectInfo.locationVOList,
            "this.projectInfo.locationVOList"
          );
          if (this.projectInfo.locationVOList) {
            this.calculateDistance(0, point1);
          } else {
            let point2 = new plus.maps.Point(
              this.projectInfo.longitude,
              this.projectInfo.latitude
            );
            console.log(this.projectInfo.longitude, this.projectInfo.latitude);
            plus.maps.Map.calculateDistance(
              point1,
              point2,
              (e) => {
                console.log(e.distance, "单点");
                if (e.distance > 500) {
                  console.log(this.byCode);
                  if (this.byCode == "1") {
                    this.isCode = true;
                  }
                  uni.showModal({
                    title: "当前定位距离项目位置超过500m，确认继续操作？",
                    success: function (res) {
                      if (res.confirm) {
                        console.log("距离" + e.distance);
                      } else {
                        uni.navigateBack();
                      }
                    },
                  });
                }
              },
              (error) => {}
            );
          }
        },
        fail: (error) => {
          uni.hideLoading();
          uni.showToast({
            title: "获取定位失败",
            icon: "none",
          });
        },
      });
    },
    // 获取检测分类
    getTypes() {
      getTypes().then((res) => {
        this.listDataOriginal = JSON.parse(JSON.stringify(res.data));
        this.listData = JSON.parse(JSON.stringify(res.data));
        console.log(this.listData, "this.listData", 1);
      });
    },
    // 下一步
    next() {
      if (this.typeId == "") {
        uni.showToast({ title: "请选择检测材料分类", icon: "none" });
        return false;
      }
      let sampleInfo = uni.getStorageSync("sampleInfo");
      // 保存定位，分类id
      sampleInfo.longitude = this.longitude;
      sampleInfo.latitude = this.latitude;
      sampleInfo.typeId = this.typeId;
      sampleInfo.typeName = this.typeName;
      uni.setStorageSync("sampleInfo", sampleInfo);
      uni.navigateTo({
        url:
          "/pages/sample/index?randomPostion=" +
          this.randomPostion +
          "&specimenNums=" +
          this.specimenNums,
      });
    },
    // 处理定位距离
    calculateDistance(num, point1) {
      if (num < this.projectInfo.locationVOList.length) {
        let point2 = new plus.maps.Point(
          this.projectInfo.locationVOList[num].longitude,
          this.projectInfo.locationVOList[num].latitude
        );
        plus.maps.Map.calculateDistance(
          point1,
          point2,
          (e) => {
            console.log(e.distance, "多点");
            if (e.distance > 500) {
              if (this.byCode == "1") {
                this.isCode = true;
              }
              console.log(num, this.projectInfo.locationVOList.length);
              if (num == this.projectInfo.locationVOList.length - 1) {
                uni.showModal({
                  title: "当前定位距离项目位置超过500m，确认继续操作？",
                  success: function (res) {
                    if (res.confirm) {
                      console.log("距离" + e.distance);
                    } else {
                      uni.navigateBack();
                    }
                  },
                });
              }
              this.calculateDistance(num + 1, point1);
            }
          },
          (error) => {}
        );
      }
    },
    // 搜索
    input(e) {
      this.searchData = e;
      if (e.length == 0) {
        this.filterdata(e);
      }
    },
    // 搜索确认
    confirmSearch(e) {
      this.filterdata(e.value);
    },
    confirmClear(e) {
      this.filterdata();
    },
    cancel(e) {
      this.filterdata();
    },
    blur(e) {
      this.searchFalg = false;
      this.filterdata(e.value);
    },
    focus(e) {
      this.searchFalg = true;
    },
    // 过滤数据
    filterdata(e) {
  if (e) {
    const filteredData = JSON.parse(JSON.stringify(this.listDataOriginal)).map(item => {
      // 过滤二级
      item.children = item.children.filter(child => {
        // 过滤三级
        if (child.children) {
          child.children = child.children.filter(subChild => 
            subChild.name.includes(e)
          );
        }
        // 保留条件：当前二级项匹配，或三级有匹配项
        return child.name.includes(e) || (child.children && child.children.length);
      });
      return item;
    }).filter(item => item.children.length > 0); // 保留有有效子项的一级

    this.listDataFlag = filteredData.length === 0;
    this.listData = filteredData;
  } else {
    this.listDataFlag = false;
    this.listData = this.listDataOriginal;
  }
}
  },
};
</script>
<style lang="scss" scoped>
#position {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  map {
    width: 100vw;
    height: 240px;
    flex-shrink: 0;
  }
.search-container{
  flex-shrink: 0;
}
.list-scroll-view {
  flex: 1;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 80px; /* 给底部按钮留空间 */
}

/* 折叠面板内部滚动 */
/deep/ .uni-collapse-item__wrap {
  max-height: 50vh;
  overflow-y: auto;
}

  .list {
    width: 100vw;
    height: calc(100vh - 284px);
     overflow-y: auto !important;
      min-height: 0; /* 关键！防止 Flex 子项无限扩展 */
    .content {
      padding: 0 20px 10px 20px;
    }
    /deep/ .uni-list-item__container {
      padding: 4px;
    }
    /deep/ .uni-list-item__content {
      justify-content: center;
    }
  }
  .list2{
    padding: 0 6px;
  }
/deep/ .uni-collapse {
  height: 100%;
  overflow: hidden;
}
/deep/ .uni-collapse-item__wrap {
  overflow-y: auto;
}
  .bottom-nav {
    left: 0;
    bottom: 0;
    width: 100vw;
    height: 50px;
    padding: 10px;
    position: fixed;
    background-color: #fff;
    box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, 0.1);
  }
  .hint {
    background: #414144;
    position: fixed;
    width: 380rpx;
    top: 50%;
    left: 50%;
    margin-left: -190rpx;
    margin-top: -25px;
    text-align: center;
    border-radius: 10rpx;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
  }
  .noData {
    margin-top: 5%;
    width: 100%;
    text-align: center;
    font-size: 24rpx;
    color: #91939a;
  }
}
</style>
